import '../enum/MessageType.dart';

class UserMessageModel {
  final int id;
  final int senderId;
  final int receiverId;
  late String content;
  late MessageType type;
  final DateTime sendTime;
  late int readStatus; // 0 未读, 1 已读

  UserMessageModel({
    required this.id,
    required this.senderId,
    required this.receiverId,
    required this.content,
    required this.type,
    required this.sendTime,
    required this.readStatus,
  });

  /// 从 JSON 转换
  factory UserMessageModel.fromJson(Map<String, dynamic> json) {
    return UserMessageModel(
      id: json['id'] is int ? json['id'] : int.tryParse(json['id'].toString()) ?? 0,
      senderId: json['senderId'] is int ? json['senderId'] : int.tryParse(json['senderId'].toString()) ?? 0,
      receiverId: json['receiverId'] is int ? json['receiverId'] : int.tryParse(json['receiverId'].toString()) ?? 0,
      content: json['content']?.toString() ?? '',
      type: _parseMessageType(json['type']),
      sendTime: DateTime.tryParse(json['sendTime']?.toString() ?? '') ?? DateTime.now(),
      readStatus: json['readStatus'] is int ? json['readStatus'] : int.tryParse(json['readStatus'].toString()) ?? 0,
    );
  }

  /// 转为 JSON
  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "senderId": senderId,
      "receiverId": receiverId,
      "content": content,
      "type": type.name.toUpperCase(),
      "sendTime": sendTime.toIso8601String(),
      "readStatus": readStatus,
    };
  }

  /// 类型解析
  static MessageType _parseMessageType(dynamic value) {
    if (value == null) return MessageType.text;
    final str = value.toString().toLowerCase();
    switch (str) {
      case "text":
        return MessageType.text;
      case "image":
        return MessageType.image;
      case "video":
        return MessageType.video;
      case "emoji":
        return MessageType.emoji;
      default:
        return MessageType.text;
    }
  }
}